﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using zhangmenren.IService;
using zhangmenren.Models;
using zhangmenren.Models.help;
using zhangmenren.Untils;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace zhangmenren.Controllers
{
    public class ApplyController : Controller
    {
		private IApplyService applyService;

        private IRealService realService;
		public ApplyController(IRealService _realService,IApplyService _applyService)
		{
			applyService = _applyService;
            realService = _realService;

        }


		// GET: /<controller>/
		public IActionResult Index()
        {
            var user = QTCookie.GetCookie<UserCook>(HttpContext);
            if (user == null)
            {
                return Redirect("/Login/Index");
            }
            return View();
        }

        /// <summary>
        /// 认证
        /// </summary>
        /// <returns>The zheng.</returns>
        public IActionResult RenZheng()
        {
            var user = QTCookie.GetCookie<UserCook>(HttpContext);
            if (user == null)
            {
                return Redirect("/Login/Index");
            }
            return View();
        }
        public IActionResult RenZhengSuccess()
        {
            return View();
        }

        [HttpPost]
		public async Task<JsonResult> AjaxApply(ApplyEntity entity)
		{
			var user = QTCookie.GetCookie<UserCook>(HttpContext);

			var list = await applyService.FindByUserId(user.Id);
			if (list.Any())
			{
				if (list.FirstOrDefault().State == 0)
				{
					return Json(new { state = "fail", msg = "请耐心等待审核" });
				}
				else if (list.FirstOrDefault().State == 1)
				{
					return Json(new { state = "fail", msg = "已通过审核,请勿重复提交." });
				}
			}
            entity.UserId = user.Id;

			var result = await applyService.Add(entity);

			return Json(new { state = "ok", msg = "提交成功" });
		}


        [HttpPost]
        public async Task<JsonResult> AjaxRenZhane(RealEntity entity)
        {
            var user = QTCookie.GetCookie<UserCook>(HttpContext);

            var real = await realService.FindByUser(user.Id);
            if (!string.IsNullOrEmpty(real?.Name))
            {
                if (real.State == 0)
                {
                    return Json(new { state = "fail", msg = "请耐心等待审核" });
                }
                else if (real.State == 1)
                {
                    return Json(new { state = "fail", msg = "已通过审核,请勿重复提交." });
                }
            }
            entity.UserId = user.Id;

            var result = await realService.Add(entity);

            return Json(new { state = "ok", msg = "提交成功" });
        }


    }
}
